/**
 * 项目授权
 */
define(function (require, exports, module) {
    var angular = require('angular');
    var $ = require('jquery');
    var ui = require('ui');
    var util = require('util');
    var _ = require('underscore');

    require('./role_common');

    angular.module('projectRole', ['roleCommon'])
        .factory('url', [
            function () {
                return {
                    //给url添加search字符串
                    addParam: function (url, search) {
                        for (var key in search) {
                            if (search.hasOwnProperty(key) && search[key]) {
                                var connecter = "&";
                                if (url.indexOf('?') === -1) {
                                    connecter = "?";
                                }
                                url += connecter + key + '=' + encodeURIComponent(search[key]);
                            }
                        }
                        return url;
                    }
                };
            }
        ])
        .service('commonAuthService', ["$http", 'url', function ($http, url) {
            var service = {
                saveAuthInfo: function (data, search) {
                    search = search || '';
                    data = data || {};
                    data['NEED_TOKEN'] = false;
                    var apiurl = '/api/index.php?r=project/auth/save-binding-auth';
                    if (angular.isObject(search)) {
                        search = angular.extend(search || {}, {rnd: +new Date()});
                        apiurl = url.addParam(apiurl, search);
                    } else {
                        apiurl += search
                    }
                    data = $.extend(data, {"USE_FORM_DATA": false});
                    return $http.post(apiurl, data)
                },
                getAuthInfo: function (data, search) {
                    search = search || '';
                    data = data || {}
                    data['params'] = data['params'] || {};
                    data['params']['NEED_TOKEN'] = false;
                    var apiurl = '/api/index.php?r=project/auth/get-org-application-list';
                    if (angular.isObject(search)) {
                        search = angular.extend(search || {}, {rnd: +new Date()});
                        apiurl = url.addParam(apiurl, search);
                    } else {
                        apiurl += search
                    }
                    return $http.get(apiurl, data);
                },
                checkCanBind: function (data, search) {
                    search = search || '';
                    data = data || {}
                    data['params'] = data['params'] || {};
                    data['params']['NEED_TOKEN'] = false;
                    var apiurl = '/api/index.php?r=project/auth/check-project-binding-app';
                    if (angular.isObject(search)) {
                        search = angular.extend(search || {}, {rnd: +new Date()});
                        apiurl = url.addParam(apiurl, search);
                    } else {
                        apiurl += search
                    }
                    return $http.get(apiurl, data);
                },
                checkCanCancel: function (data, search) {
                    search = search || '';
                    data = data || {}
                    data['params'] = data['params'] || {};
                    data['params']['NEED_TOKEN'] = false;
                    var apiurl = '/api/index.php?r=project/auth/check-cancel-project-binding-app';
                    if (angular.isObject(search)) {
                        search = angular.extend(search || {}, {rnd: +new Date()});
                        apiurl = url.addParam(apiurl, search);
                    } else {
                        apiurl += search
                    }
                    return $http.get(apiurl, data);
                }
            }
            return service;

        }])
        .controller('projectRoleCtl', ['$rootScope', '$scope', '$q', 'commonAuthService', function ($rootScope, $scope, $q, commonAuthService) {


            function getProjBindInfo() {
                var data = {};
                commonAuthService.getAuthInfo(data, {projectId: $scope.curProjectId}).then(function (res) {
                    if (res && res.data && res.data.retCode == 0) {
                        $scope.projAuthList = res.data.data.data;
                        $scope.cur_bind_mode = res.data.data.isUpgrade;

                        _.each($scope.projAuthList, function (item) {
                            item.total_num = _.reduce(item.contracts, function(memo, item){ return memo + parseInt(item.total_num); }, 0);
                            item.use_num = _.reduce(item.contracts, function(memo, item){ return memo + parseInt(item.use_num); }, 0);
                            _.each(item.contracts, function (cont_item) {
                                cont_item.type = 'init';
                            });
                        });
                    }
                });
            }


            //新模式 掌上售楼处必须有一个绑定项才能绑其他的
            $scope.check_can_bind = function () {
                var binded = [];
                _.each($scope.projAuthList, function (item) {
                    if (item.isZsslc) {
                        binded = _.filter(item.contracts, function (cont_item) {
                            return cont_item.binding == 1;
                        });
                    }
                });
                return binded;
            };
            //新模式 掌上售楼处的最后一项取消绑定时其它的必须都取消
            $scope.check_can_cancel = function () {
                var binded = $scope.check_can_bind(), otherBinded = [];
                if (binded.length == 1) {
                    _.each($scope.projAuthList, function (item) {
                        if (!item.isZsslc) {
                            otherBinded = otherBinded.concat(_.filter(item.contracts, function (cont_item) {
                                return cont_item.binding == 1;
                            }));
                        }
                    });
                }
                return otherBinded;

            };

            $scope.continue_bindAuth = function (item, cont_item) {
                var binded = $scope.check_can_bind();
                if ($scope.cur_bind_mode && !item.isZsslc && !binded.length > 0 || $scope.canEdit == 0) {//非掌上售楼处
                    return;
                }
                if (cont_item.type == 'delete') {
                    cont_item.binding = 1;
                    cont_item.use_num++;
                    cont_item.type = 'init';
                    return;
                }

                var data = {
                    applicationCode: item.Application,
                    projectId: $scope.curProjectId,
                    authorizeId: cont_item.authorize_id
                };

                commonAuthService.checkCanBind({}, data).then(function (res) {
                    if (res.data.retCode == 0) {
                        cont_item.binding = 1;
                        cont_item.use_num++;
                        if (cont_item.type == 'init') {
                            cont_item.type = 'add';
                        }
                        $scope.saveBindInfo('授权成功！');
                    }
                })
            };

            //绑定授权
            $scope.bindAuth = function (item, cont_item) {
                if (item.Application == '5030') {
                    util.confirm('绑定云Call客前，请检查并确认项目已经绑定移动销售及全民营销两个应用，是否继续绑定?',
                        {
                            ok: function () {
                                $scope.continue_bindAuth(item, cont_item);
                            },
                            cancel: function () {
                            },
                            okValue: '继续绑定'
                        })
                } else {
                    $scope.continue_bindAuth(item, cont_item);
                }


            };

            //应用至少保留一个有效的绑定授权
            $scope.islastAvailableContract = function (item, cont_item) {
                var binded = _.filter(item.contracts, function (cont_item) {
                    var end = false;
                    var s_time = null;
                    if (!SERVER_TIME) {
                        s_time = new Date();
                    } else {
                        s_time = new Date(SERVER_TIME.replace(/(\d{4})-(\d{2})-(\d{2})(.*)/g, '$1/$2/$3$4'));
                    }
                    if (cont_item.EndOn) {
                        end = new Date(cont_item.EndOn.replace(/(\d{4})-(\d{2})-(\d{2})(.*)/g, '$1/$2/$3$4')) < SERVER_TIME;
                    } else {
                        end = true;
                    }

                    return cont_item.binding == 1 && !end;
                });
                return binded.length == 1;
            };

            //取消绑定
            $scope.cancelAuth = function (item, cont_item) {
                var binded = $scope.check_can_cancel();
                if ($scope.cur_bind_mode && item.isZsslc && binded.length > 0 || $scope.canEdit == 0) {//掌上售楼处
                    return;
                }
                if (cont_item.type == 'add') {
                    cont_item.binding = 0;
                    cont_item.use_num--;
                    cont_item.type = 'init';
                    return;
                }
                var data = {
                    applicationCode: item.Application,
                    projectId: $scope.curProjectId,
                    authorizeId: cont_item.authorize_id
                };
                commonAuthService.checkCanCancel({}, data).then(function (res) {
                    if (res.data.retCode == 0) {
                        if (res.data.data && $scope.islastAvailableContract(item, cont_item)) {
                            util.alert('项目已绑定公众号,至少保留一个有效授权');
                            return;
                        }
                        cont_item.binding = 0;
                        cont_item.use_num--;
                        if (cont_item.type == 'init') {
                            cont_item.type = 'delete';
                        }
                        $scope.saveBindInfo('取消授权成功！');

                    }
                })
            };

            //保存更改了的授权信息
            $scope.saveBindInfo = function (msg) {
                msg || (msg = '操作成功！');
                if ($scope.canEdit == 0) {
                    return
                }
                var data = [];
                _.each($scope.projAuthList, function (item) {
                    _.each(item.contracts, function (cont_item) {
                        if (cont_item.type != 'init') {
                            data.push({
                                ProjectId: $scope.curProjectId,
                                ApplicationCode: item.Application,
                                AuthorizeId: cont_item.authorize_id,
                                type: cont_item.type
                            })
                        }
                        ;
                    })
                });
                commonAuthService.saveAuthInfo({auth: data}).then(function (res) {
                    if (res.data.retCode == 0) {
                        ui.showSucTip(msg);
                        setTimeout(function () {
                            getProjBindInfo();
                        }, 2500);
                    }
                });
            };
            $scope.$on('changeCurProjectId', function (event, curProjectId) {
                $scope.curProjectId = curProjectId;
                getProjBindInfo();
            });
            $scope.$on('changeCanEdit', function (event, canEdit) {
                $scope.canEdit = canEdit;
            });
            if ($scope.curProjectId) {
                getProjBindInfo();
            }

        }])
});